const Router = require('koa-router')
const router = new Router({
    prefix: "/api/admin/admin"
})

const Admin = require('../../models/admin')
const {
    Success
} = require('../../utils/response')

router.get('/admin', async (ctx) => {

    let adminList = await Admin.findAll({
        where: {
            code: 0
        }
    })

    ctx.body = Success(adminList)
})

router.get('/admininfo', async (ctx) => {

    let {
        id
    } = ctx.request.query
    let adminList = await Admin.findAll({
        where: {
            id
        }
    })
    ctx.body = Success(adminList);

})

router.post('/admin', async (ctx) => {

    let {
        username,
        password,
    } = ctx.request.body
    if (!username || !password) {
        ctx.body = Error('未携带指定参数')
    } else {
        let user = await Admin.findOne({
            where: {
                username
            }
        })
        if (!user) {
            let user = await Admin.create({
                username,
                password,
                code: 0
            })
            ctx.body = Success(user, '添加成功');
        } else {
            ctx.body = Success('', '该用户已经存在');
        }

    }


})

router.put('/admin', async (ctx) => {

    let {
        id,
        username,
        password
    } = ctx.request.body
    if (!id || !username || !password) {
        ctx.body = Error('未携带指定参数')
    } else {
        let user = await Admin.update({
            username,
            password,
        }, {
            where: {
                id
            }
        })
        if (user[0] == 1) {
            ctx.body = Success('', '修改成功');
        } else {
            ctx.body = Success('', '修改失败');
        }

    }


})

router.delete('/admin', async (ctx) => {

    let {
        id,
    } = ctx.request.body
    if (!id) {
        ctx.body = Error('未携带指定参数')
    } else {
        let user = await Admin.destroy({
            where: {
                id
            }
        })
        if (user == 1) {
            ctx.body = Success('', '删除成功');
        } else {
            ctx.body = Success('', '删除失败');
        }
    }

})



module.exports = router